package com.neusoft.utils.string;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 * 
 * @author Administrator
 * 
 */
public class StringUtil extends org.apache.commons.lang3.StringUtils {

	/**
	 * 如果参数的第一个字符是小写的 ，那就转化为大写的
	 * 
	 * @param input
	 *            长度大于1的String ,大于1是我们的一个约定
	 * @return
	 */
	public static String firstChar2Upcase(String input) throws NullPointerException {
		if (input == null || input.length() < 1)
			throw new NullPointerException();
		char[] chars = input.toCharArray();
		if (chars[0] >= 'a' && chars[0] <= 'z')
			return (char) (chars[0] + ('A' - 'a')) + input.substring(1);
		else {
			return input;
		}
	}

	/**
	 * 计算字符长度，如果是null就是-1
	 * 
	 * @param input
	 * @return
	 */
	public static int getStringLength(String input) {
		if (input == null)
			return -1;
		return input.length();
	}

	/**
	 * 如果第一个字符为大写则转换为小写
	 * 
	 * @param input
	 * @return
	 * @throws NullPointerException
	 */
	public static String firstChar2Downcase(String input) throws NullPointerException {
		if (input == null || input.length() < 1)
			throw new NullPointerException();
		char[] chars = input.toCharArray();
		if (chars[0] >= 'A' && chars[0] <= 'Z')
			return (char) (chars[0] - ('A' - 'a')) + input.substring(1);
		else {
			return input;
		}
	}

	/**
	 * 将enumeration里面的string首字母转换为大写的
	 * 
	 * @param strs
	 * @return
	 * @throws NullPointerException
	 */
	public static ArrayList<String> firstChar2Upcase(Enumeration<String> strs, ArrayList<String> oldList) throws NullPointerException {
		if (strs == null)
			throw new NullPointerException();
		ArrayList<String> list = new ArrayList<String>();
		while (strs.hasMoreElements()) {
			String string = (String) strs.nextElement();
			oldList.add(string);
			list.add(firstChar2Upcase(string));

		}
		return list;
	}

	/**
	 * 将null值转换为空字符串
	 * 
	 * @param input
	 * @return
	 */
	public static String toNotNullString(String input) {
		return input == null ? "" : input.trim();
	}

	/**
	 * 转换为非null字符串
	 * 
	 * @param input
	 * @param defaultString
	 * @return
	 */
	public static String toNotNullString(String input, String defaultString) {
		return input == null ? defaultString : input.trim();
	}

	/**
	 * 将空字符串和null转换为默认值
	 * 
	 * @param input
	 * @param defaultString
	 * @return
	 */
	public static String toNotNullAndSpaceString(String input, String defaultString) {
		return input == null ? defaultString : input.equals("") ? defaultString : input.trim();
	}

	/**
	 * 将空字符串和null值转换为-1
	 * 
	 * @param input
	 * @return
	 */
	public static String toNotNullNumberString(String input, String defaultString) {
		return input == null ? defaultString : input == "" ? defaultString : input.trim();
	}

	/**
	 * 如果input为NUll或为空就返回defaultString，否则返回input
	 * 
	 * @param input
	 * @param defaultString
	 * @return
	 */
	public static String toDefault(String input, String defaultString) {
		if (input == null || input.equals(""))
			return defaultString;
		return input.trim();
	}

	/**
	 * 对url编码的字符串解码,url编码的原编码为UTF-8
	 * 
	 * @param input
	 * @return
	 */
	public static String decodeURL(String input) {
		if (input == null)
			return null;
		try {
			return URLDecoder.decode(input, "UTF-8").trim();
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		return input.trim();
	}

	public static String encodeURL(String input) {
		if (input == null)
			return null;
		try {
			return URLEncoder.encode(input, "UTF-8").trim();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return input.trim();
	}

	public static String getNowTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String dateString = formatter.format(currentTime);
		return dateString;
	}

	/**
	 * 字符串转换成List
	 * 
	 * @param str
	 * @param format
	 * @return
	 */
	public static List<Integer> stringToList(String str, String format) {
		if (str == null || "".equals(str)) {
			return null;
		}
		String[] tmp = str.split(format);
		List<Integer> list = new ArrayList<Integer>();
		for (String s : tmp) {
			list.add(Integer.parseInt(s));
		}
		return list;
	}

	public static String getStrOfList(List<String> list, String format) {
		StringBuilder result = new StringBuilder();
		if (null != null && list.size() > 0) {
			if (list.size() == 1) {
				result.append(list.get(0));
			} else {
				for (int index = 0; index < list.size(); index++) {
					String str = list.get(index);
					result.append(str);
					if (index != list.size() - 1) {
						result.append(format);
					}
				}
			}
		}
		return result.toString();
	}

	/**
	 * 生成不带_的uuid
	 * 
	 * @return 32位的uuid
	 */
	public static String uuid() {
		String uuid = UUID.randomUUID().toString();
		return StringUtil.remove(uuid, "-");
	}

	/**
	 * 简单模板实现 String str = "I'm not a {0}, age is {1,number,short}", height is
	 * {2,number,#.#};
	 * 
	 * @param pattern
	 * @param arguments
	 * @return String
	 */
	public static String format(String pattern, Object... arguments) {
		MessageFormat temp = new MessageFormat(pattern);
		return temp.format(arguments);
	}

	public static Boolean isNull(Object obj) {
		if (null == obj) {
			return true;
		}
		String str = String.valueOf(obj);
		if (StringUtil.isBlank(str)) {
			return true;
		}
		return false;
	}

	public static Boolean isNotNull(Object obj) {
		return !isNull(obj);
	}

	public static boolean find(String str, String regex) {
		Matcher m = Pattern.compile(regex).matcher(str);
		return m.find();
	}

	// 过滤特殊字符
	public static String StringFilter(String str) {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public static String strNums(String str, String split, int num) {
		if (num == 0) {
			return "";
		}
		StringBuffer fullStr = new StringBuffer();
		for (int i = 0; i < num; i++) {
			fullStr.append(str).append(split);
		}
		return fullStr.substring(0, fullStr.length() - split.length());
	}

	public static String strList(List<String> strs, String split) {
		if (null == strs || strs.size() == 0) {
			return "";
		}
		StringBuffer fullStr = new StringBuffer();
		for (String string : strs) {
			fullStr.append(string).append(split);
		}
		return fullStr.substring(0, fullStr.length() - split.length());
	}

	public static String captureFirst(String name) {
		char[] cs = name.toCharArray();
		cs[0] -= 32;
		return String.valueOf(cs);
	}

	public static String joinStr(String split, String... strs) {
		StringBuffer sb = new StringBuffer();
		for (String str : strs) {
			if (!isBlank(str)) {
				sb.append(str).append(split);
			}
		}
		if ("".equals(sb.toString())) {
			return "";
		}
		return sb.substring(0, sb.length() - split.length()).toString();
	}

}
